/**
 * This file is part of CommaTuner.
 * Copyright 2011 Gabriel G Mendonça (gabrielgmendonca@gmail.com)
 * 
 * CommaTuner is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * CommaTuner is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with CommaTuner.  If not, see <http://www.gnu.org/licenses/>.
 */

package br.mendonca.commatuner;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import br.mendonca.audio.analysis.PitchDetector;

public class CommaTunerActivity extends Activity implements OnClickListener {
	private static final int SAMPLE_RATE = 16000;
	private static final int BUFFER_SIZE = 8192;

	private PitchDetector pitchDetector;
	private PitchView pitchView;
	private PitchDetectionThread pitchThread;

	private Button button;

	private boolean isTuning = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		pitchDetector = new PitchDetector(SAMPLE_RATE, BUFFER_SIZE);

		button = (Button) findViewById(R.id.button);
		button.setOnClickListener(this);

		pitchView = (PitchView) findViewById(R.id.pitch);
	}

	@Override
	public void onClick(View v) {
		if (!isTuning) {
			startThread();
			button.setText(R.string.button_tuning);
		} else {
			stopThread();
			button.setText(R.string.button_idle);
		}

		isTuning = !isTuning;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		stopThread();
		pitchDetector.destroy();
	}

	private void startThread() {
		pitchThread = new PitchDetectionThread(pitchDetector, pitchView);
		pitchThread.active = true;
		pitchThread.start();
	}

	private void stopThread() {
		if (pitchThread != null) {
			pitchThread.active = false;
	
			boolean retry = true;
			while (retry) {
				try {
					pitchThread.join();
					retry = false;
				} catch (InterruptedException e) {
				}
			}
		}
	}
}
